package util

import (
	"fmt"
	"log"
	"mp3/entity"
	"os"
	"os/exec"
	"strings"
)

var HEADERS = []string{"Cache-Control", "Connection", "Content-Encoding", "Content-Type", "Vary", "content-length", "access-control-allow-methods", "User-Agent", "Server", "Content-Length", "content-type"}

func IsEmpty(str string) bool {

	return len(str) == 0
}

func IsNotEmpty(str string) bool {
	return !IsEmpty(str)
}

func ExistStr(str string, switchStr string) bool {
	if IsEmpty(str) {
		return false
	}

	return strings.Index(str, switchStr) > -1
}

/*格式化标题*/
func FormatTitle(title string, index int) string {
	builder := strings.Builder{}
	builder.WriteString("1")
	builder.WriteString(FormatTitle1(index, titleLength))
	builder.WriteString("_")

	builder.WriteString(title)

	return builder.String()
}

func FormatTitle1(index int, length int) string {
	builder := strings.Builder{}
	len := length - len(fmt.Sprintf("%d", index))
	for i := 0; i < len; i++ {
		builder.WriteString("0")
	}
	builder.WriteString(fmt.Sprintf("%d", index))

	return builder.String()
}

/*
判断文件是否存在
@parent fileName 文件名称
@parent configEntity  配置文件
*/
func SwitchFileExsts(playEntity entity.PlayListEntity, config entity.DownloadEntity) bool {
	for _, fileName := range playEntity.TitleNames {
		fp := CombinationFielPath(config.FileDirPath, fileName) + config.AudioType
		_, e := os.Stat(fp)
		if !os.IsNotExist(e) {

			cmd := exec.Command(strings.TrimSpace(config.FFprobe), "-show_format", strings.TrimSpace(fp))
			err := cmd.Run()
			exec.Command("exit")
			cmd.Run()

			if nil != err {
				log.Println(fp, err)
				os.Remove(fp)
				return false
			}

			flag := ValudateFile(config, fp)
			if !flag {
				return false
			}

			_, error := os.Stat(fp)
			if nil != error {
				log.Println(fp, err)
				return false
			}

			if strings.LastIndex(fileName, ".1.") < 0 {
				ClearAttr(fp, config, fileName, "")
			}
			return true
		}

	}

	return false
}

func SwitchIndex(index int, count int) int {
	index++
	if count <= index {
		index = 0
	}

	return index
}

func SwitchArr(arr []int, val int) bool {
	len := len(arr)
	for i := 0; i < len; i++ {
		if val == arr[i] {
			return true
		}
	}
	return false
}

func MergeHead(urlHeadMap map[string]string, urlHeadMap1 map[string]string) map[string]string {
	header := make(map[string]string)
	if len(urlHeadMap) > 0 {
		for key := range urlHeadMap {
			header[key] = urlHeadMap[key]
		}
	}

	if len(urlHeadMap1) > 0 {
		for key := range urlHeadMap1 {
			header[key] = urlHeadMap1[key]
		}
	}

	return header
}

func ContainsStr(slice []string, element string) bool {
	for _, e := range slice {
		if strings.ToLower(e) == strings.ToLower(element) {
			return true
		}
	}
	return false
}
